﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using NCS.IConnect.ApplicationContexts;
using Microsoft.SharePoint;
using JM.JCY.Proxy;
using JM.JCY.BusinessEntity;
using JM.JCY.Common;
using System.Data;
using JM.JCY.Common.Utilities;
using System.IO;
using System.Threading;
using System.Text;

namespace JM.JCY.SharePointComponent.PhotoAlbum.AddAlbum
{
    public partial class AddAlbumUserControl : UserControl
    {
        public string appType
        {
            set;
            get;
        }
        public int appId
        {
            set;
            get;
        }
        public int _staffId
        {
            set;
            get;
        }

        public DataTable sessionKeys
        {
            get
            {
                DataTable dt = new DataTable();
                DataColumn dc = new DataColumn();
                dc.ColumnName = "fileType";
                dt.Columns.Add(dc);

                DataColumn dc2 = new DataColumn();
                dc2.ColumnName = "fileKey";
                dt.Columns.Add(dc2);

                DataColumn dc3 = new DataColumn();
                dc3.ColumnName = "fileTypeName";
                dt.Columns.Add(dc3);

                DataColumn dc4 = new DataColumn();
                dc4.ColumnName = "filePath";
                dt.Columns.Add(dc4);

                DataColumn dc5 = new DataColumn();
                dc5.ColumnName = "orgFileName";
                dt.Columns.Add(dc5);

                return dt;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            LoadApplicationContext();
            if (!IsPostBack)
            {
                string ocpurl = System.Configuration.ConfigurationManager.AppSettings["JCYUrl"].ToString();
                if (ocpurl.EndsWith("/"))
                {
                    ocpurl = ocpurl.Substring(0, ocpurl.Length - 1);
                }
                HiddenFieldOcpUrl.Value = ocpurl;
            }
            string CreateAlbum = Request.Params.Get("__EVENTTARGET");
            if (CreateAlbum != null && CreateAlbum.IndexOf("CreateAlbum") > -1)
            {
                BtnSave_Click(null, null);
            }
        }

        private void LoadApplicationContext()
        {
            appId = 0;
            appType = JCYConstant.PhotoAlbum.ApplicationTypeName.PublicName;
            _staffId = 1;
        }
        protected void BtnSave_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                DataTable tableKeys = getFilesDetailToDataTable();
                SPWeb CurrentWeb = SPContext.Current.Web;
                int albumId = 0;
                using (PhotoAlbumProxy funProxy = new PhotoAlbumProxy())
                {
                    SPInputs createAlbumInput = new SPInputs();
                    List<byte[]> mediaList = new List<byte[]>();
                    List<string> mediaExtension = new List<string>();
                    DataTable mediaTable = new DataTable();
                    DataColumn dc1 = new DataColumn();
                    dc1.ColumnName = "FilePath";
                    mediaTable.Columns.Add(dc1);
                    DataColumn dc2 = new DataColumn();
                    dc2.ColumnName = "PicPath";
                    mediaTable.Columns.Add(dc2);

                    #region ready data for inputs
                    byte[] picBytes;
                    string picName=string.Empty;
                    foreach (DataRow keyRow in tableKeys.Rows)
                    {
                        picName = Guid.NewGuid().ToString().Replace("-", "");
                        if (keyRow["fileType"].ToString().Equals("pic"))
                        {
                            // pic type
                            mediaExtension.Add("." + keyRow["fileTypeName"].ToString());
                            if (Session[keyRow["fileKey"].ToString()] != null)
                            {
                                byte[] mediaStream = (byte[])Session[keyRow["fileKey"].ToString()];
                                mediaList.Add(mediaStream);
                            }
                        }
                    }

                    createAlbumInput.MediaStream = mediaList;
                    createAlbumInput.MediaExtension = mediaExtension;
                    createAlbumInput.ApplicationType = appType;
                    createAlbumInput.SiteName = SPContext.Current.Web.Title;
                    createAlbumInput.ContextID =appId.ToString();
                    createAlbumInput.AlbumName = this.txtAlbumName.Text;
                    createAlbumInput.MediaTable =null;// mediaTable;

                    createAlbumInput.SharingOption = "";
                    #endregion

                    SPOutputs spout = JCYSharePointHelper.CreateFolderWithUpload(createAlbumInput);
                    if (!spout.IsError)
                    {
                        #region insert Data to DB
                        DataTable outTable = spout.OutputsTable;
                        string picFolderID = string.Empty, mediaFolderID = string.Empty;

                        var albumDS = new PhotoAlbumDataSet();
                        foreach (DataRow r in outTable.Rows)
                        {
                            if (r[1].ToString().Equals(string.Empty))
                            {

                                picFolderID = r["FolderID"].ToString();
                                r.Delete();
                                break;
                            }
                        }
                        //AccessFrameworkDataSet.T_OcpApplicationDataTable applicationdt;
                        //applicationdt = GetApplicationByName(OCPConstant.ListName.FunWork);

                        var newAlbumRow = albumDS.T_Album.NewT_AlbumRow();
                        for (int i = 0; i < outTable.Rows.Count; i++)
                        {
                            DataRow outRow = outTable.Rows[i];
                            //insert album table
                            if (i == 0)
                            {
                                //insert sharepoint object table.
                                var newAlbumObjectRow = albumDS.T_SharePointObject.NewT_SharePointObjectRow();
                                newAlbumObjectRow.SPSiteName = appType;
                                newAlbumObjectRow.SPListName = appType;// JCYConstant.ListName.FunWork;
                                newAlbumObjectRow.SPFolderId = picFolderID;
                                //newAlbumObjectRow.ApplicationId = applicationdt[0].ApplicationId;
                                //newAlbumObjectRow.SharePointObjectType = JCYConstant.AlbumType.FunWorkAlbum;
                                newAlbumObjectRow.IsDeleted = false;

                               JCYUtility.UpdateCommonFields(newAlbumObjectRow, "a");
                                albumDS.T_SharePointObject.AddT_SharePointObjectRow(newAlbumObjectRow);

                                //insert album table
                                newAlbumRow.SharePointObjectId = newAlbumObjectRow.SharePointObjectId;
                                newAlbumRow.Name = this.txtAlbumName.Text;
                                newAlbumRow.Description = this.txtAlbumDescription.Text.Length > 256 ? this.txtAlbumDescription.Text.Substring(0, 256) : this.txtAlbumDescription.Text;
                                newAlbumRow.ItemCount = 0;
                                newAlbumRow.ViewCount = 0;
                                newAlbumRow.LikeCount = 0;
                                newAlbumRow.AppId = appId;
                                newAlbumRow.AppType = appType;
                                newAlbumRow.Creator = _staffId;
                                newAlbumRow.LatestUpdateTime = DateTime.Now;
                                newAlbumRow.IsDeleted = false;
                                newAlbumRow.ThumbNailImgUrl = "";
                                JCYUtility.UpdateCommonFields(newAlbumRow, "a");
                                albumDS.T_Album.AddT_AlbumRow(newAlbumRow);
                            }

                            // insert sharepoint object table

                            var newObjectRow = albumDS.T_SharePointObject.NewT_SharePointObjectRow();
                            newObjectRow.SPSiteName = appType;
                            newObjectRow.SPListName ="";
                            newObjectRow.SPFolderId = outRow["FolderID"].ToString();
                            newObjectRow.SPListItemId = outRow["ItemID"].ToString();
                            newObjectRow.IsDeleted = false;
                            JCYUtility.UpdateCommonFields(newObjectRow, "a");
                            albumDS.T_SharePointObject.AddT_SharePointObjectRow(newObjectRow);

                            // insert album content table  
                            var newAlbumContentRow = albumDS.T_AlbumContent.NewT_AlbumContentRow();
                            newAlbumContentRow.AlbumId = newAlbumRow.AlbumId;
                            newAlbumContentRow.ThumbNailImgUrl = outRow["ThumbNailImgUrl"].ToString();
                            newAlbumContentRow.OriginalImgUrl = outRow["OriginalImgUrl"].ToString();
                            newAlbumContentRow.OptimizeImgUrl = outRow["OptimizeImgUrl"].ToString();
                            newAlbumContentRow.StaffId = _staffId;
                            newAlbumContentRow.Description = string.Empty;
                            newAlbumContentRow.IsDeleted = false;
                            newAlbumContentRow.SharePointObjectId = newObjectRow.SharePointObjectId;
                            JCYUtility.UpdateCommonFields(newAlbumContentRow, "A");
                            albumDS.T_AlbumContent.AddT_AlbumContentRow(newAlbumContentRow);
                            newAlbumRow.ItemCount += 1;
                            newAlbumRow.ThumbNailImgUrl = outRow["ThumbNailImgUrl"].ToString();
                        }

                        funProxy.CreateAlbumwithUpload(albumDS);
                        albumId = albumDS.T_Album[0].AlbumId;
                        #endregion
                    }
                    else
                    {
                        return;
                    }
                    //clear all session byte[].
                    foreach (DataRow keyRow in tableKeys.Rows)
                    {
                        if (Session[keyRow["fileKey"].ToString()] != null)
                        {
                            Session.Remove(keyRow["fileKey"].ToString());
                        }
                    }
                    tableKeys.Rows.Clear();
                }
                Response.Redirect("ViewAlbum.aspx?AlbumId=" + albumId);
                
            }
            catch (Exception ex)
            {
                bool isok = JCYUtility.ExceptionHandle("create album", ex);
                if (isok == false)
                {
                    throw ex;
                }
            }
        }

        private string GetMediaType(string originalImgUrl)
        {
            string picType = "jpg|jpeg|gif|tif|bmp|png";

            string mediaType = string.Empty;
            string typeName = originalImgUrl.Substring(originalImgUrl.LastIndexOf(".") + 1).ToLower();
            if (picType.IndexOf(typeName) > -1)
            {
                mediaType = "Pic";
            }

            return mediaType;
        }

        public DataTable getFilesDetailToDataTable()
        {
            DataTable dt = sessionKeys;
            try
            {
                string uploadPath = System.Configuration.ConfigurationManager.AppSettings["uploadPath"].ToString();
                uploadPath = Context.Server.MapPath(uploadPath);
                if (uploadPath.EndsWith("\\") == false)
                {
                    uploadPath = uploadPath + "\\";
                }

                string logFileName = HiddenFieldGuid.Value.Replace("-", "") + ".txt";
                if (File.Exists(uploadPath + logFileName))
                {
                    string[] fileLines = File.ReadAllLines(uploadPath + logFileName);

                    foreach (string stg in fileLines)
                    {
                        string[] fileDetail = stg.Split(new char[] { '?' });
                        DataRow row = dt.NewRow();
                        //row["fileType"] = "pic";
                        //row["filePath"] = uploadPath + fileName;
                        //row["fileTypeName"] = fileTypeName;
                        //row["orgFileName"] = file.FileName;
                        if (fileDetail[0].Equals("pic"))
                        {
                            FileStream fs = new FileStream(fileDetail[1], FileMode.Open, FileAccess.Read);
                            byte[] fileBuffer = new byte[fs.Length];
                            fs.Read(fileBuffer, 0, fileBuffer.Length);
                            fs.Close();
                            fs.Dispose();

                            string fileKey = Guid.NewGuid().ToString();
                            Session[fileKey] = fileBuffer;

                            row["fileType"] = fileDetail[0];
                            row["fileKey"] = fileKey;
                            row["filePath"] = fileDetail[1];
                            row["fileTypeName"] = fileDetail[2];
                            row["orgFileName"] = fileDetail[3];

                        }
                        dt.Rows.Add(row);
                    }
                }
                else
                {
                    throw new Exception("Can not find files log detail information:" + uploadPath + logFileName);
                }
            }
            catch (Exception ex)
            {
                JCYUtility.ExceptionHandle("getFilesDetails", ex);
            }

            return dt;
        }
    }
}
